package com.iuweb.commen.es;

import com.iuweb.commen.controller.BaseController;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author ruiwu
 * @version V1.0
 * @Description:ElasticSearchClientFactoryBean
 */
public class ElasticSearchClientFactoryBean extends BaseController implements FactoryBean<Client>{

    private String clusterName = "nini";
    private String host = "192.168.239.135";
    private Integer port = 9300;

    public String getClusterName() {
        return clusterName;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    @SuppressWarnings("resource")
    @Override
    public Client getObject() throws Exception {
        try {
            //设置集群名称
            Settings settings = Settings.builder()
                    .put("cluster.name", clusterName)
                    .build();
            //创建client
            TransportClient client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new TransportAddress
                            (InetAddress.getByName(host), port));
            logger.info("success to connect"+host+":名"+clusterName);
            return client;
        } catch (UnknownHostException e) {
            logger.error("error to connect"+host+":名"+clusterName);
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
